package com.knowledgegraph.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knowledgegraph.common.Result;
import com.knowledgegraph.entity.Entity;
import com.knowledgegraph.service.EntityService;
import com.knowledgegraph.service.impl.EntityServiceImpl;
import com.knowledgegraph.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实体管理控制器
 * 
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/entities")
public class EntityController {

    @Autowired
    private EntityService entityService;
    
    @Autowired
    private EntityServiceImpl entityServiceImpl;

    /**
     * 分页查询实体列表
     */
    @PostMapping("/list")
    public Result<Map<String, Object>> getEntities(@RequestBody Map<String, Object> params) {
        
        int page = (Integer) params.getOrDefault("page", 1);
        int pageSize = (Integer) params.getOrDefault("pageSize", 10);
        String searchText = (String) params.get("searchText");
        String type = (String) params.get("type");
        
        try {
            log.info("查询实体列表 - page: {}, pageSize: {}, searchText: {}, type: {}", 
                    page, pageSize, searchText, type);
            
            // 构建分页对象
            Page<Entity> pageObj = new Page<>(page, pageSize);
            
            // 构建查询参数
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("searchText", searchText);
            queryParams.put("type", type);
            queryParams.put("creatorId", SecurityUtil.getCurrentUserId()); // 只查询当前用户的数据
            
            // 执行分页查询
            IPage<Entity> result = entityServiceImpl.getEntitiesWithPagination(pageObj, queryParams);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("data", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("pageSize", result.getSize());
            
            return Result.success(data);
            
        } catch (Exception e) {
            log.error("查询实体列表失败", e);
            return Result.error("查询实体列表失败: " + e.getMessage());
        }
    }

    /**
    /**
     * 获取统计数据
     */
    @PostMapping("/stats")
    public Result<Map<String, Object>> getStats() {
        try {
            Long currentUserId = SecurityUtil.getCurrentUserId();
            log.info("获取统计数据 - 用户ID: {}", currentUserId);
            
            Map<String, Object> stats = entityServiceImpl.getUserStatistics(currentUserId);
            
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }

/**
     * 获取用户统计数据
     */
    @PostMapping("/user-stats")
    public Result<Map<String, Object>> getUserStats() {
        try {
            Long currentUserId = SecurityUtil.getCurrentUserId();
            log.info("获取用户统计数据 - 用户ID: {}", currentUserId);
            
            Map<String, Object> stats = entityServiceImpl.getUserStatistics(currentUserId);
            
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取用户统计数据失败", e);
            return Result.error("获取用户统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取实体详情
     */
    @PostMapping("/detail")
    public Result<Entity> getEntityById(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            log.info("获取实体详情 - id: {}", id);
            
            Entity entity = entityService.getById(id);
            if (entity == null) {
                log.error("实体不存在 - id: {}", id);
                
                // 调试：打印所有实体ID
                List<Entity> allEntities = entityService.list();
                log.info("当前数据库中的所有实体ID: {}", 
                    allEntities.stream().map(Entity::getId).collect(java.util.stream.Collectors.toList()));
                
                return Result.error("实体不存在，ID: " + id);
            }
            
            return Result.success(entity);
            
        } catch (Exception e) {
            log.error("获取实体详情失败", e);
            return Result.error("获取实体详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建实体
     */
    @PostMapping("/create")
    public Result<Entity> createEntity(@RequestBody @Valid Entity entity) {
        try {
            log.info("创建实体 - name: {}, type: {}", entity.getName(), entity.getType());
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityService.createEntity(entity, currentUserId);
            
            if (success) {
                return Result.success("创建成功", entity);
            } else {
                return Result.error("创建失败");
            }
            
        } catch (Exception e) {
            log.error("创建实体失败", e);
            return Result.error("创建实体失败: " + e.getMessage());
        }
    }

    /**
     * 更新实体
     */
    @PostMapping("/update")
    public Result<Entity> updateEntity(@RequestBody Map<String, Object> params) {
        
        Long id = Long.valueOf(params.get("id").toString());
        @SuppressWarnings("unchecked")
        Map<String, Object> entityData = (Map<String, Object>) params.get("entity");
        
        Entity entity = new Entity();
        entity.setName((String) entityData.get("name"));
        entity.setType((String) entityData.get("type"));
        entity.setDescription((String) entityData.get("description"));
        
        try {
            log.info("更新实体 - id: {}, name: {}, type: {}", id, entity.getName(), entity.getType());
            
            // 先检查实体是否存在
            Entity existingEntity = entityService.getById(id);
            if (existingEntity == null) {
                log.error("更新实体失败: 实体不存在, ID: {}", id);
                return Result.error("实体不存在，ID: " + id);
            }
            
            entity.setId(id);
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityService.updateEntity(entity, currentUserId);
            
            if (success) {
                // 返回更新后的实体
                Entity updatedEntity = entityService.getById(id);
                return Result.success("更新成功", updatedEntity);
            } else {
                return Result.error("更新失败：数据库操作失败");
            }
            
        } catch (Exception e) {
            log.error("更新实体失败", e);
            return Result.error("更新实体失败: " + e.getMessage());
        }
    }

    /**
     * 删除实体
     */
    @PostMapping("/delete")
    public Result<Void> deleteEntity(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            log.info("删除实体 - id: {}", id);
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityService.deleteEntity(id, currentUserId);
            
            if (success) {
                return Result.success("删除成功",null);
            } else {
                return Result.error("删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除实体失败", e);
            return Result.error("删除实体失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除实体
     */
    @PostMapping("/batch-delete")
    public Result<Void> batchDeleteEntities(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) params.get("ids");
        try {
            log.info("批量删除实体 - ids: {}", ids);
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityService.batchDeleteEntities(ids, currentUserId);
            
            if (success) {
                return Result.success("批量删除成功",null);
            } else {
                return Result.error("批量删除失败");
            }
            
        } catch (Exception e) {
            log.error("批量删除实体失败", e);
            return Result.error("批量删除实体失败: " + e.getMessage());
        }
    }

    /**
     * 导入实体
     */
    @PostMapping("/import")
    public Result<Map<String, Object>> importEntities(
            @RequestParam("file") MultipartFile file) {
        
        try {
            log.info("导入实体 - filename: {}", file.getOriginalFilename());
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            Map<String, Object> result = entityServiceImpl.importEntitiesFromFile(file, currentUserId);
            
            return Result.success("导入完成",result);
            
        } catch (Exception e) {
            log.error("导入实体失败", e);
            return Result.error("导入实体失败: " + e.getMessage());
        }
    }

    /**
     * 导出实体
     */
    @PostMapping("/export")
    public void exportEntities(@RequestBody Map<String, Object> params, HttpServletResponse response) {
        
        String searchText = (String) params.get("searchText");
        String type = (String) params.get("type");
        @SuppressWarnings("unchecked")
        List<Long> selectedIds = (List<Long>) params.get("selectedIds");
        
        try {
            log.info("导出实体 - searchText: {}, type: {}, selectedIds: {}", 
                    searchText, type, selectedIds);
            
            Map<String, Object> exportParams = new HashMap<>();
            exportParams.put("searchText", searchText);
            exportParams.put("type", type);
            exportParams.put("selectedIds", selectedIds);
            
            entityServiceImpl.exportEntitiesToExcel(exportParams, response);
            
        } catch (Exception e) {
            log.error("导出实体失败", e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入错误响应失败", ioException);
            }
        }
    }
}